package com.hugoo.core.db.rp;

import com.hugoo.rpt.ExpPageInfo;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;

/**
 *
 * @author Lovelock.Chan
 */
public class TxtResultPack extends ResultPack {

    public TxtResultPack(ExpPageInfo pi, String[][] col) {
        super(pi, col);
    }

    @Override
    public void packResult(ResultSet rs) {
        FileWriter fr = null;
        try {
            ///////验证列/////////////////
            pi.validateColumn(rs.getMetaData());
            /////////////////////////////
            fr = new FileWriter(pi.getTempFile());
            if (pi.isExpTitle()) {//如果需要导出标题行,执行本部分(默认是导出标题行)
                for (String fl : col[1]) {
                    fr.append(fl).append("|");
                }
            }
            StringBuffer sb = new StringBuffer();
            int i = 0, k = col[0].length;
            boolean haveEnd = pi.haveEnd();
            while (rs.next()) {
                if (pi.isExpTitle() || i > 0) {
                    sb.append("\r\n");//换行
                }
                for (int j = 0; j < k; j++) {
                    if (haveEnd) {
                        sb.append(getValue(rs, col[0][j])).append("|");
                    } else {
                        sb.append(getValue(rs, col[0][j]));
                        if (j < k - 1) {
                            sb.append("|");
                        }
                    }
                }
                if (i++ % 200 == 0) {
                    fr.write(sb.toString());
                    sb = new StringBuffer();
                }
            }
            fr.write(sb.toString());
        } catch (Exception ex) {
            log.warn("处理Txt数据导出时，出现异常！", ex);
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException ex) {
                log.warn("关闭Txt文件时，出现异常！", ex);
            }
        }
    }
}
